10.1 Creating tuples
1. What is a tuple? What is its key feature?
A tuple is an ordered collection of elements. Its key feature is immutability: once created, its values cannot be changed, added or removed. It is very similar to a list except for this. Tuples store fixed sets of information such as geographical coordinates and dates.
2. How is a tuple created? What is tuple packing?
Enclose elements in parentheses separated by commas: numbers = (10, 20, 30, 40). Parentheses are optional; values separated by commas are automatically treated as a tuple. This is tuple packing:
>>> hilly_areas = "Munnar", "Ponmudi", "Sholayoor", "Vagamon"
>>> print(hilly_areas)
('Munnar', 'Ponmudi', 'Sholayoor', 'Vagamon')3. Can a tuple hold mixed data types? Why does append() not work on tuples?
Yes: t = ("apple", "grapes", 2, 23, 2.5). Tuples do not have all the methods of lists; append() does not work because tuples are immutable.
4. How is a tuple with a single element created? How is an empty tuple created?
A comma must follow the single element. Without the comma Python treats it as a normal value.
>>> t1 = (1984,)
>>> type(t1)
<class 'tuple'>
>>> t2 = (78)
>>> type(t2)
<class 'int'>
>>> t3 = () # empty tuple5. Write a program that creates one variable with a string in parentheses without a comma and another with a comma, and displays their types.
a = ("Python")
b = ("Python",)
print(type(a)) # <class 'str'>
print(type(b)) # <class 'tuple'>Parentheses alone do not make a tuple; the comma does.
6. Predict the output and explain: x = (10) / print(type(x)) / y = (10,) / print(type(y))
<class 'int'>
<class 'tuple'>(10) is just the integer 10 in brackets; (10,) has a trailing comma, so it is a one-element tuple.
10.2–10.3 Accessing and slicing
7. How are tuple elements accessed? What happens for an index that does not exist?
By index, starting at 0, as in lists: marks = (85, 90, 78, 92); marks[0] → 85; marks[3] → 92. marks[4] raises an IndexError (tuple index out of range), since the last valid index is 3.
8. Explain negative indexing with days.
Negative values index from the right: the last element is –1. For days = ("Monday", …, "Sunday"), days[-1] → 'Sunday' and days[-3] → 'Friday'. It is useful for reaching elements from the end without calculating their positions.
9. Explain tuple slicing. What are the defaults for start and end?
Syntax: tuple_name[start:end]; it returns elements from start up to but excluding end. If start is omitted it is 0; if end is omitted the slice runs to the end. Negative indices can be used. The result is a new tuple.
10. Explain slicing with a step value using step_value = (5,10,15,20,25,30,35,40).
Syntax: tuple_name[start:end:step]. The step is how many positions to move; a negative step reverses direction (rules same as for strings).
| Expression | Result | Meaning |
|---|---|---|
step_value[::2] | (5, 15, 25, 35) | Every second element from the start |
step_value[1::2] | (10, 20, 30, 40) | From index 1, every second element |
step_value[2:7:3] | (15, 30) | Index 2, ends before 7, step 3 |
step_value[::-1] | (40, 35, 30, 25, 20, 15, 10, 5) | Whole tuple reversed |
step_value[-2::-2] | (35, 25, 15, 5) | From second last, backward by 2 |
11. For t = (12, 24, 36, 48, 60, 72) write scripts to print: (i) first and third elements (ii) the last element (iii) the second last element.
t = (12, 24, 36, 48, 60, 72)
print(t[0], t[2]) # 12 36
print(t[-1]) # 72
print(t[-2]) # 6012. For the same tuple display (a) the first three elements (b) elements from index 2 to the end (c) the three middle elements.
print(t[:3]) # (12, 24, 36)
print(t[2:]) # (36, 48, 60, 72)
print(t[1:4]) # (24, 36, 48) three middle elementsWith six elements, t[2:5] = (36, 48, 60) is also an acceptable choice of "middle three".
10.4–10.5 Immutability and concatenation
13. Explain immutability of tuples using T1 = (10, 20, 30) and T2 = T1.
Tuples are objects in memory and variable names are references. After T2 = T1, both refer to the same tuple object. Because tuples are immutable, the elements of that object cannot be modified through either name. Trying T1[0] = 100 raises a TypeError (tuple object does not support item assignment). We can only create a new tuple, not change an existing one.
14. What is concatenation of tuples? Is the original tuple modified?
Joining tuples with +.
>>> T1 = (10, 20, 30)
>>> T2 = T1 + (40,)
>>> print(T2)
(10, 20, 30, 40)Python creates a new tuple holding all elements; T2 refers to it while T1 still refers to the original (10, 20, 30). Note the comma in (40,).
15. Write a program to concatenate two tuples containing names of ancient Greek philosophers.
t1 = ("Socrates", "Plato")
t2 = ("Aristotle", "Pythagoras")
print(t1 + t2)Output: ('Socrates', 'Plato', 'Aristotle', 'Pythagoras')
16. What is tuple unpacking? How is it related to packing?
Unpacking is the reverse of packing: the individual values in a tuple are assigned to separate variables in a single statement, matched in order. The number of variables must equal the number of elements.
>>> t = (10, 20, 30)
>>> a, b, c = t
>>> print(a, b, c)
10 20 30Packing and unpacking are useful when functions return multiple values or handle variable-length arguments.
17. Pack the title, author and price of a book into a tuple; create a tuple of your name, class and favourite subject; concatenate odd and even tuples.
book = ("Wings of Fire", "A. P. J. Abdul Kalam", 350)
print(book)
me = ("Asha", "XI", "Computer Science")
print(me[0]); print(me[1]); print(me[2])
odd = (1, 3, 5, 7)
even = (2, 4, 6, 8)
print(odd + even) # (1, 3, 5, 7, 2, 4, 6, 8)10.6.1 Membership operators
18. Explain in and not in with tuples.
in is True if the element exists in the tuple; not in is True if it does not.
>>> numbers = (10, 20, 30, 40, 50)
>>> print(20 in numbers)
True
>>> print(100 in numbers)
False19. How does membership work with nested tuples? Explain with total_score.
in checks for a whole element, not parts of it. For total_score = ((20,40,60),(18,39,45),(17,34,40)):
>>> (20, 40, 60) in total_score
True
>>> 40 in total_score
FalseThe first is True because that exact tuple is one of the elements. The second is False because 40 is inside a sub-tuple, not an element of the outer tuple.
20. Check whether 25 is present in nums = (10, 15, 20, 25, 30, 35); print "Found!" or "Not Found!".
nums = (10, 15, 20, 25, 30, 35)
if 25 in nums:
print("Found!")
else:
print("Not Found!")Output: Found!
21. What is the output? animals = ('Cat','Dog','Rabbit') / print('dog' in animals) / print('Dog' in animals)
False
TrueString comparison is case sensitive: 'dog' is not the same as 'Dog'.
10.6.2 Conversions and assignment
22. How are lists and tuples converted into each other? Why would we do so?
With the built-in tuple() and list(), which create a new object. This lets us switch between the mutability of a list and the immutability (security and stability) of a tuple.
>>> my_list = [1, 2, 3]
>>> my_tuple = tuple(my_list)
>>> print(my_tuple)
(1, 2, 3)
>>> t = (4, 5, 6)
>>> l = list(t)
>>> print(l)
[4, 5, 6]To "change" a tuple, convert it to a list, modify the list, and convert it back.
23. Can a tuple contain a list? Can that list be modified?
Yes. The tuple is immutable, but a mutable member such as a list inside it can still be changed (the tuple keeps the same reference to the list). In the cart example, the cart is a tuple (customer name, total amount, list of items); cart[2].append("Headphone") adds an item to the list although the tuple itself is unchanged.
def update_cart(cart, new_item):
print("Before:", cart)
cart[2].append(new_item)
print("After:", cart)
cart = ("Anu", 1500, ["Pen", "Book"])
update_cart(cart, "Headphone")
# After: ('Anu', 1500, ['Pen', 'Book', 'Headphone'])24. Explain tuple assignment for swapping variables.
Normally a temporary variable is needed:
temp = a
a = b
b = tempTuple assignment swaps in one line: a, b = b, a. Python packs the right side into a tuple (b, a) and unpacks it into a and b. With a = 5 and b = 10, afterwards a = 10 and b = 5.
10.6.3 Functions on tuples
25. Which methods do tuples have? Explain count() and index().
Only two built-in methods: count() and index().
>>> marks = (90, 80, 90, 70, 90)
>>> marks.count(90)
3
>>> ai_words = ("Chatbot", "NLP", "LLM", "ANN", "Chatbot")
>>> ai_words.index("Chatbot")
0count() gives how many times a value appears; index() gives the first position where it appears.
26. Explain len(), max(), min(), sum() and all() on tuples.
| Function | Description | Example (marks = (90, 80, 90, 70, 90)) |
|---|---|---|
len() | Number of elements | len(("pen","book","bag")) → 3 |
max() | Largest element (alphabetically last for strings) | 90 |
min() | Smallest element | 70 |
sum() | Sum of numeric elements | 420 |
all() | True if all elements are truthy; False if any is False, 0 or empty | True |
27. Predict the output: (A) A = (10,20,30,40,50); print(A[-1], A[2:4]) (B) E = (100,200,300,400,500); print(E[1], E[2:])
(A) 50 (30, 40)
(B) 200 (300, 400, 500)
28. Store India's neighbouring countries in a tuple in decreasing order of border length; print the first and last country alphabetically.
neighbours = ("Bangladesh", "China", "Pakistan", "Nepal",
"Myanmar", "Bhutan", "Afghanistan")
print("First alphabetically:", min(neighbours)) # Afghanistan
print("Last alphabetically:", max(neighbours)) # PakistanThe order follows commonly quoted land border lengths (Bangladesh about 4,096 km down to Afghanistan about 106 km); please verify the figures from your atlas or textbook. min() and max() work alphabetically on strings.
10.7 Tuple applications
29. Why are tuples suitable for fixed data? Give examples.
Data that must not change accidentally is best stored in a tuple: a student's admission record (ID, Name, Class), coordinates (x, y), fixed currency denominations, dates.
30. Write the currency denomination analyser (Figure 10.10).
Denominations are fixed, so they go in a tuple; counts go in a list because they change.
def denomination_generator(amount):
notes = (500, 200, 100, 50, 20, 10)
counts = []
for note in notes:
counts.append(amount // note)
amount = amount % note
print("Denomination Count")
used = []
for i in range(len(notes)):
if counts[i] != 0:
print(notes[i], "x", counts[i])
used.append(counts[i])
print("Types of notes used:", len(used))
print("Maximum notes of one type:", max(used))
print("Total notes:", sum(used))
if amount != 0:
print("Balance not payable with these notes:", amount)
amt = int(input("Enter the amount: "))
denomination_generator(amt)For 1780: 500×3, 200×1, 50×1, 20×1, 10×1 → 5 types, maximum 3, total 7 notes.
31. Write the 2D point distance program (Figure 10.11).
Distance = √((x2 – x1)² + (y2 – y1)²). Each point is a tuple (x, y) because it always has exactly two fixed values.
import math
def read_points():
x = float(input("Enter x: "))
y = float(input("Enter y: "))
return (x, y)
def distance(p1, p2):
return math.sqrt((p2[0] - p1[0]) ** 2 + (p2[1] - p1[1]) ** 2)
pt1 = read_points()
pt2 = read_points()
print("Point 1:", pt1, "Point 2:", pt2)
print("Distance =", distance(pt1, pt2))For (1, 2) and (4, 6): distance = √(9 + 16) = 5.0.
32. Create a list of 14 (code, district) tuples for Kerala and write PrintDistrict() and PrintCode().
districts = [(1, "Thiruvananthapuram"), (2, "Kollam"), (3, "Pathanamthitta"),
(4, "Alappuzha"), (5, "Kottayam"), (6, "Idukki"), (7, "Ernakulam"),
(8, "Thrissur"), (9, "Palakkad"), (10, "Malappuram"),
(11, "Kozhikode"), (12, "Wayanad"), (13, "Kannur"), (14, "Kasaragod")]
def PrintDistrict(code):
for c, name in districts:
if c == code:
print("District:", name)
return
print("Invalid code")
def PrintCode(name):
for c, d in districts:
if d.lower() == name.lower():
print("Code: KL-%02d" % c)
return
print("District not found")
choice = input("Enter 1 to search by code, 2 to search by name: ")
if choice == "1":
PrintDistrict(int(input("Enter district code: ")))
else:
PrintCode(input("Enter district name: "))33. Read 10 points as tuples, then another point, and find the closest using findClosest().
import math
def findClosest(p, points):
closest = points[0]
best = math.sqrt((p[0]-closest[0])**2 + (p[1]-closest[1])**2)
for q in points:
d = math.sqrt((p[0]-q[0])**2 + (p[1]-q[1])**2)
if d < best:
best = d
closest = q
return closest
points = []
for i in range(10):
x = float(input("x: ")); y = float(input("y: "))
points.append((x, y))
x = float(input("Given point x: ")); y = float(input("Given point y: "))
print("Closest point:", findClosest((x, y), points))The function keeps the smallest distance seen so far and returns the tuple that produced it.
34. Store a student's details (name, age, grade, state) in a tuple and unpack them.
student = ("Meera", 16, "A", "Kerala")
name, age, grade, state = student
print("Name:", name)
print("Age:", age)
print("Grade:", grade)
print("State:", state)35. Bus route: print the first and last stops, show the index of a stop entered by the user, and the number of stops.
stops = ("Kakkanad", "Edappally", "Vyttila", "Kaloor", "Ernakulam South")
print("First stop:", stops[0])
print("Last stop:", stops[-1])
name = input("Enter a stop name: ")
if name in stops:
print("Index:", stops.index(name))
else:
print("Stop not on this route")
print("Number of stops:", len(stops))36. Book collection: write functions to find the total, repetitions of a title, first position, alphabetical first and last titles, and availability.
books = ("When Breath Become Air", "Atomic Habits", "Snow",
"Rubaiyat of Omar Khayyam", "The Alchemist",
"Diary of a Wimpy Kid", "Atomic Habits")
def total(): print("Total books:", len(books))
def repetition(t): print(t, "appears", books.count(t), "time(s)")
def position(t):
if t in books: print("First position (index):", books.index(t))
else: print("Not found")
def alphabetical(): print("First:", min(books), "| Last:", max(books))
def available(t):
print("Available" if t in books else "Not available")
total() # 7
repetition("Atomic Habits") # 2
position("Atomic Habits") # 1
alphabetical() # First: Atomic Habits | Last: When Breath Become Air
available("Snow") # Available37. Differentiate between a list and a tuple.
| List | Tuple |
|---|---|
| Mutable | Immutable |
Square brackets [ ] | Parentheses ( ) (or just commas) |
| Many methods (append, insert, remove…) | Only count() and index() |
| Used for data that changes | Used for fixed, protected data |
Single element: [5] | Single element needs a comma: (5,) |